package com.ktjy.util.filter;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.PropertyPreFilter;
import com.alibaba.fastjson2.filter.ValueFilter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Set;

public class FastJson2DateValueFilter implements ValueFilter {

    private LinkedHashMap<String, String> dateMappings;

    public FastJson2DateValueFilter(
            LinkedHashMap<String, String> dateMappings) {
        this.dateMappings = dateMappings;
    }

    @Override
    public Object apply(Object object, String propertyName, Object value) {
        if (dateMappings == null) {
            return value;
        }
        // 要判断数据类型,只处理 Date 类型
        if (value instanceof Date) {
            Set<String> keySet = dateMappings.keySet();
            for (String pattern : keySet) {
                // 循环所有的正则表达式，判断属性名是否符合正则要求
                if (propertyName.matches(pattern)) {
                    // 符合要求的取出格式进行转换
                    String dateFormat = dateMappings.get(pattern);
                    // 返回对应格式
                    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
                    return formatter.format((Date) value);
                }
            }
        }
        return value;
    }
}
